package com.sdp.th.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.sdp.core.bizc.threadLocal.ContextManager;
import com.sdp.core.bizc.utils.CoreConstantsEnum;
import com.sdp.core.bizc.vo.BusinessContext;
import com.sdp.core.bizc.vo.Result;
import com.sdp.right.control.SysLoginLogController;
import com.sdp.right.db.sys_emp.service.ISysEmpService;
import com.sdp.right.entity.SysEmp;
import com.sdp.right.utils.RsaUtil;
@RestController
@RequestMapping("/AppLoginController")
public class AppLoginController {
	
	@Autowired
	private ISysEmpService iSysEmpService;
	
	@Autowired
	private SysLoginLogController sysLoginLogController;
	
	@Autowired
	HttpServletRequest request;

	@Value("${sdp.rightMode}")
	private boolean rightMode;

	/**
	 * 原来没有RSA加密的登录
	 * @param sysEmp
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value = "/login")
	public Result<?> login(@RequestBody SysEmp sysEmp) throws Exception{
		if(sysEmp==null) {
			return Result.error("登录信息为空");
		}
		BusinessContext businessContext = iSysEmpService.login(sysEmp);
		if(businessContext.isSuccess()) {
			RsaUtil.cleanKeyMap();
			//记录登录日志
			sysLoginLogController.addLoginLog(businessContext.get(sysEmp.getClass()));
			return Result.ok(JSONObject.toJSON(businessContext.get("token")));
		}else {
			return Result.error(businessContext.getMessage());
		}
	}
	
	
	/**
	 * 根据TOKEN获取用户权限信息
	 * @return
	 */
	@GetMapping(value = "/info")
	public Result<?> info(){
		String token = request.getHeader(CoreConstantsEnum.header中的token参数名.getCode());
		String systemNo = ContextManager.getContextData(CoreConstantsEnum.header中的模块参数名.getCode());
		BusinessContext businessContext = iSysEmpService.permissionInfo(rightMode, token, systemNo);
		if(businessContext.isSuccess()) {
			return Result.ok(JSONObject.toJSON(businessContext.get("permissionInfo")));
		}else {
			return Result.error(businessContext.getMessage());
		}
	}
}
